package org.sss.tcpserver.main;

import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

import org.sss.interestrates.Interestrates.CurvePoint;
import org.sss.interestrates.Interestrates.interestRateCurve;

public class P2PCollector {
	
	private static int port = 8090;
	private ServerSocket socket;
	
	public void init() {
		try {
			socket = new ServerSocket(port,10);
			System.out.println("Created socket "+socket);
			Socket sock = socket.accept();
			InputStream is = sock.getInputStream();
			OutputStream os = sock.getOutputStream();
			while (true) {
				byte[] slen = new byte[3];
				is.read(slen);
				System.out.println("Read header length " + new String(slen));
				byte[] barr = new byte[Integer.parseInt(new String(slen))];
				is.read(barr);
				//String protobin = new String(barr);
				interestRateCurve icurve = interestRateCurve.parseFrom(barr);
				System.out.println(icurve.toString());				
				for (CurvePoint cp:icurve.getDeposit().getCurvepointList()) {
					System.out.println(cp.getTenor()+","+cp.getMaturitydate()+","+cp.getParrate());
				}
				for (CurvePoint cp:icurve.getSwap().getCurvepointList()) {
					System.out.println(cp.getTenor()+","+cp.getMaturitydate()+","+cp.getParrate());
				}
				os.write("OK".getBytes());
				os.flush();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		P2PCollector coll = new P2PCollector();
		coll.init();
	}

}
